//
//  VCWeb.swift
//  AirlineReservation
//
//  Created by Kevin on 2020/2/4.
//  Copyright © 2020 Kevin. All rights reserved.
//

import UIKit
import WebKit

class VCWeb: VCBase,WKNavigationDelegate,WKUIDelegate {
    
    // 进度条
    private lazy var progressView: UIProgressView = {
        let ui = UIProgressView()
        ui.frame = CGRect(x: 0, y: realHeight, width: SCREEN_WIDTH, height: 2)
        ui.tintColor = UIColor.orange
        ui.trackTintColor = UIColor.white
        return ui
    }()
    
    // 网页界面
    private lazy var wkWebView: WKWebView = {
        // 适配手机
        let userScprit = WKUserScript(source: WEB_SCRIPT, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        // 用户偏好
        let wkUser = WKUserContentController()
        wkUser.addUserScript(userScprit)
        // 网页视图
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.userContentController = wkUser
        // 显示尺寸
        let uiY = progressView.frame.maxY + MARGIN5
        let uiframe = CGRect(x: 0, y: uiY, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - uiY)
        let ui = WKWebView(frame: uiframe, configuration: webConfiguration)
        ui.uiDelegate = self
        ui.navigationDelegate = self
        ui.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        return ui
    }()
    
    // MARK: 访问的页面
    public var pageapi:String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        init_set()
        init_view()
        init_event()
    }
    
    func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
        let response = navigationResponse.response as! HTTPURLResponse
        if response.statusCode == 200 {
            decisionHandler(.allow)
        }else{
            decisionHandler(.cancel)
        }
    }
    
    func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
        self.show(text: "请检查网络连接，是否正确")
    }
    
    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: { (action) in
            completionHandler()
        }))
        present(alert, animated: true, completion: nil)
    }
    
    deinit {
        self.wkWebView.removeObserver(self, forKeyPath: "estimatedProgress")
    }
}

extension VCWeb {
    
    private func init_event() -> Void {
        // 访问页面
        guard let page = pageapi else {
            return
        }
        // IP地址
        var spip = UserDefaults.standard.string(forKey: SP_IP)
        if spip == nil {
            spip = SP_INNTER
        }
        // 完成地址
        guard let url = URL(string: "\(spip!)\(page)") else {
            return
        }
        print("ffffffff =\(url)")
        // 加载网页
        wkWebView.load(URLRequest(url: url))
    }
    
    //  加载进度条
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "estimatedProgress"{
            progressView.alpha = 1.0
            progressView.setProgress(Float((self.wkWebView.estimatedProgress) ), animated: true)
            if (self.wkWebView.estimatedProgress )  >= 1.0 {
                UIView.animate(withDuration: 0.3, delay: 0.1, options: .curveEaseOut, animations: {
                    self.progressView.alpha = 0
                }, completion: { (finish) in
                    self.progressView.setProgress(0.0, animated: false)
                })
            }
        }
    }
    
    private func init_view() -> Void {
        view.backgroundColor = UIColor.white
        view.addSubview(wkWebView)
        view.addSubview(progressView)
    }
    
    private func init_set() -> Void {
        view.backgroundColor = UIColor.white
    }
}
